//日期格式化过滤器
Date.prototype.format = function(fmt) { //author: meizz 
	var o = {
		'M+': this.getMonth() + 1, //月份 
		'd+': this.getDate(), //日 
		'h+': this.getHours(), //小时 
		'm+': this.getMinutes(), //分 
		's+': this.getSeconds(), //秒 
		'q+': Math.floor((this.getMonth() + 3) / 3), //季度 
		'S': this.getMilliseconds() //毫秒 
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[
			k]).substr(('' + o[k]).length)));
	return fmt;
};
function logInfo(i){
	console.info(i);
}
function logDebug(i){
	//console.debug(i);
}
function clientIndexEvent(e) {
	logInfo('clientIndexEvent=' + JSON.stringify(e));
	if (e["data"]["eventkey"] == "CHECK_UPDATE") {
		checkUpdate();
	} else if (e["data"]["eventkey"] == "SCREENSHOT") {
		VisualConst.clientDesktopCapturer({},function(base64){
			//logDebug(base64)
			ScreenReq.eventCallback(e, base64, function(re) {
				console.log(re);
			});
		})
	} else if (e["data"]["eventkey"] == "RESOURCE") {
		VisualConst.getMemory(function(data) {
			ScreenReq.eventCallback(e, data, function(re) {
				console.log(re);
			});
		});
	} else if (e["data"]["eventkey"] == "RELOADCONFIG") {
		//加载配置
	} else if (e["data"]["eventkey"] == "RELOADSCREEN") {
		//重新加载大屏内容
		reConnectOpen();
	}
}

function closeStartPage() {
	var startupPage = getContentScreenWebViewById("appStartupPage");
	if (startupPage) {
		startupPage.close();
	}
}

function showStartPage() {
	
	//判断横竖屏
	var url = "startup_page.h.html";
	if ('h' == VisualConst.getScreenType()) {
		url = "startup_page.h.html";
	} else if ('v' == VisualConst.getScreenType()) {
		url = "startup_page.v.html";
	}
	//打开自定义的启动页
	var startupPage = mui.openWindow({
		url: url,
		id: "appStartupPage",
		styles: {
			top: 0, //新页面顶部位置
			bottom: 0 //新页面底部位置
		},
		extras: {},
		createNew: false, //是否重复创建同样id的webview，默认为false:不重复创建，直接显示
		show: {
			autoShow: false, //页面loaded事件发生后自动显示，默认为true
			aniShow: "", //页面显示动画，默认为”slide-in-right“；
			duration: 10 //页面动画持续时间，Android平台默认100毫秒，iOS平台默认200毫秒；
		},
		waiting: {
			autoShow: false, //自动显示等待框，默认为true
			title: '正在加载...', //等待对话框上显示的提示内容
			options: {}
		}
	})
	//自定义的启动页加载后,关闭默认启动页
	//logDebug(startupPage.id);
	startupPage.show();
	plus.navigator.closeSplashscreen();//关闭5+自带的启动画面
}
//创建单个窗口
function createScreen(data) {
	if (data["data"] && data["data"]["opurl"]) {} else {
		return;
	}
	//关闭之前已创建的轮播内容展示窗口和 定时任务
	closeAllRollingScreens();
	
	var view = plus.webview.getWebviewById("contentPage");
	if (view) {
		logDebug("收到新的内容，清除历史记录");
		view.clear();
		view.loadURL(data["data"]["opurl"]);
	} else {
		view = mui.openWindow({
			url: data["data"]["opurl"],
			id: "contentPage",
			styles: {
				top: 0, //新页面顶部位置
				bottom: 0 //新页面底部位置
			},
			extras: {},
			createNew: false, //是否重复创建同样id的webview，默认为false:不重复创建，直接显示
			show: {
				autoShow: true, //页面loaded事件发生后自动显示，默认为true
				aniShow: "slide-in-right", //页面显示动画，默认为”slide-in-right“；
				duration: 200 //页面动画持续时间，Android平台默认100毫秒，iOS平台默认200毫秒；
			},
			waiting: {
				autoShow: true, //自动显示等待框，默认为true
				title: '正在加载...', //等待对话框上显示的提示内容
				options: {}
			}
		})
		view.appendJsFile('res/comm/back.js');
		view.appendJsFile('res/comm/preloadWindow.js');
		//view.show();
	}
	
}
var cScreenObjFixedtime = {
	"index": 0,
	"playtime": 0,
	"starttime": 0,
	"duration": 60,
	"durationDefault": 60,
	"winid": ""
};

var cScreenObj = {
	"index": 0,
	"playtime": 0,
	"starttime": 0,
	"duration": 60,
	"durationDefault": 15
}; //默认从头开始
//创建多个轮播窗口
var _contentlist = []; //要展示的内容集合
// [{
// 	"opurl": "http://data.avue.top/view.html?id=1",
// 	"startdate": "",
// 	"starttime": "12:05",
// 	"id": "demo001"
// }]
var _queueFixedtime = {}; //队列，定时内容,时间作为key，内容作为value
var _queueRolling = []; //队列，滚动展示内容
var _contentWindows = {}; //节目单对应的展示窗口对象集合
var task_playContentList;

function getContentScreenById(id) {
	//logDebug("getContentScreenById = " + id);
	var contentScreen = null;
	for (var i = 0; i < _contentlist.length; i++) {
		var c = _contentlist[i];
		var winid = "window_" + c.id;
		if (winid == id) {
			contentScreen = c;
			break;
		}
	}
	return contentScreen;
}

function getContentScreenWebViewById(id) {
	//logDebug("getContentScreenWebViewById = " + id);
	return plus.webview.getWebviewById(id);
}

function createContentWebView(obj) {
	//console.log("createScreens",41,JSON.stringify(obj));
	var wv = mui.openWindow({
		url: obj["url"],
		id: obj["id"],
		styles: {
			top: 0, //新页面顶部位置
			bottom: 0 //新页面底部位置
		},
		extras: {},
		createNew: false, //是否重复创建同样id的webview，默认为false:不重复创建，直接显示
		show: {
			autoShow: obj["autoShow"] || false, //页面loaded事件发生后自动显示，默认为true
			aniShow: "slide-in-right", //页面显示动画，默认为”slide-in-right“；
			duration: 200 //页面动画持续时间，Android平台默认100毫秒，iOS平台默认200毫秒；
		},
		waiting: {
			autoShow: obj["autoShow"] || false, //自动显示等待框，默认为true
			title: '正在加载...', //等待对话框上显示的提示内容
			options: {}
		}
	});
	wv.appendJsFile('res/comm/back.js');
	wv.appendJsFile('res/comm/preloadWindow.js');
	wv.addEventListener('onLoadingResource', function(e) {
		logDebug(e.url)
	}, false);
	return wv;
}

//关闭不需要的内容窗口
function closeScreensByIds() {
	var contentIds = ","
	console.log("closeScreensByIds1",contentIds);
	for (var i = 0; i < _contentlist.length; i++) {
		var c = _contentlist[i];
		var winid = "window_" + c.id;
		contentIds += winid + ",";
	}
	console.log("closeScreensByIds2",contentIds,JSON.stringify(_contentWindows));
	for (var winid in _contentWindows) {
		console.log("closeScreensByIds",winid);
		if (contentIds.indexOf("," + winid + ",") < 0) {
			_contentWindows[winid].close();
		}
	}
}

function closeAllRollingScreens() {

	//关闭窗口
	for (var key in _contentWindows) {
		if (_contentWindows[key]) {
			_contentWindows[key].close();
		}
	}
	//清空轮播列表
	_queueFixedtime = {}; //存放定时轮播窗口对象，key为日期时间，value为窗口winid
	_queueRolling = new Array(); //存放轮播窗口id集合
	_contentWindows = {};
	_contentlist = [];
	//关闭定时器
	if (task_playContentList) {
		clearInterval(task_playContentList);
	}
}

function createScreens(msg) {
	//接收推送来的内容列表
	_contentlist = msg["contentlist"] || [];
	//关闭不在本次任务中的内容窗口；之前已创建的内容展示窗口和 定时任务
	closeScreensByIds();
	//清空轮播列表
	_queueFixedtime = {}; //存放定时轮播窗口对象，key为日期时间，value为窗口winid
	_queueRolling = new Array(); //存放轮播窗口id集合
	_contentWindows = {};
	
	
	// _contentWindows = [{
	// 	"opurl": "http://data.avue.top/view.html?id=1",
	// 	"startdate": "",
	// 	"starttime": "00:13",
	// 	"duration": 150,
	// 	"id": "demo001"
	// }
	// // , {
	// // 	"opurl": "http://data.avue.top/view.html?id=9",
	// // 	"startdate": "",
	// // 	"starttime": "",
	// // 	"id": "demo002"
	// // }
	// , {
	// 	"opurl": "http://screentest.qyguanjia.com:8078/content/music2/index.html?h=16&m=16&c=3",
	// 	"startdate": "",
	// 	"starttime": "",
	// 	"duration": 20,
	// 	"id": "demo004"
	// }];

	logDebug("_contentlist = " + _contentlist.length)

	for (var i = 0; i < _contentlist.length; i++) {
		var c = _contentlist[i];
		var winid = "window_" + c.id;
		// _contentWindows[winid] = createContentWebView({"url":c["opurl"],"id":winid,"autoShow":false});

		if ((null != c.starttime && "" != c.starttime) || (null != c.startdate && "" != c.startdate)) {
			//定时的内容
			//logDebug("***************" + new Date().format("yyyy-MM-dd"));
			if (null == c.starttime || "" == c.starttime) {
				//时间为空，则表示无需定时，加入轮播队列
				_queueRolling.push(winid);
			} else {
				if (null == c.startdate || "" == c.startdate) {
					_queueFixedtime[c.starttime] = winid;
				} else {
					_queueFixedtime[c.startdate + " " + c.starttime] = winid;
				}
			}

		} else {
			_queueRolling.push(winid);
		}
	}
	startPlay(0);
	//秒级定时任务，检查需要定时播放的内容，对于定时需要播放的，到时间直接切换
	//关闭定时器
	if (task_playContentList) {
		clearInterval(task_playContentList);
	}
	task_playContentList = setInterval(playContentList, 1000);
	
	
}

function startPlay(index) {
	logDebug("开始播放的索引=" + index)
	if (_queueRolling.length <= 0) {
		//无播放列表
		logDebug("无播放列表")
		return;
	}
	for (var i = 0; i < _queueRolling.length; i++) {
		if (_contentWindows[i]) {
			//在播放下一个之前，先将全部轮播内容设置静音
			_contentWindows[i].evalJS('__stopPlay();');
		}
	}
	// for (var i of _queueRolling) {
		
	// }
	var winid = _queueRolling[index];
	var contentScreen = getContentScreenById(winid);
	startPlayByWinid(winid);
	cScreenObj.index = index;
	cScreenObj.playtime = 0; //秒
	cScreenObj.starttime = new Date().getTime(); //毫秒
	cScreenObj.duration = contentScreen["duration"] || cScreenObj["durationDefault"];
}
/**
 * 播放定时内容
 * @param {Object} winid
 */
function startPlayFixedtime(winid) {

	for (var i in _queueFixedtime) {
		if (_contentWindows[i]) {
			//在播放下一个之前，先将全部轮播内容设置静音
			_contentWindows[i].evalJS('__stopPlay();');
		}
	}
	var contentScreen = getContentScreenById(winid);
	startPlayByWinid(winid);
	cScreenObjFixedtime.winid = winid;
	cScreenObjFixedtime.playtime = 0; //秒
	cScreenObjFixedtime.starttime = new Date().getTime(); //毫秒
	cScreenObjFixedtime.duration = contentScreen["duration"] || cScreenObjFixedtime["durationDefault"];
}

function startPlayByWinid(winid) {
	logDebug("startPlayByWinid=" + winid)
	//console.log("createScreens",2,winid);
	var contentScreen = getContentScreenById(winid);
	//console.log("createScreens",3,contentScreen);
	if (_contentWindows[winid]) {
		//显示窗口
		logDebug(["当前显示+",winid ,JSON.stringify(contentScreen), _contentWindows[winid]]);
		_contentWindows[winid].show({"aniShow":"fade-in","duration":200});
		//取消静音
		_contentWindows[winid].evalJS('__startPlay();');
	} else {
		//创建窗口
		//console.log("createScreens",4,winid);
		_contentWindows[winid] = createContentWebView({
			"url": contentScreen["url"],
			"id": winid,
			"autoShow": true
		});
		//console.log("createScreens",5,_contentWindows[winid]);
		_contentWindows[winid].show({"aniShow":"fade-in","duration":200})
		logDebug("创建并显示+" + winid + "=" + contentScreen["url"]);
	}
}
//触摸页面 3 向左滑动，4向右滑动，0 没滑动
function touchContentPage(msg) {
	logDebug("touchContentPage=" + "触发了")
	var delayed = msg['delayed'] || 15;//单位秒
	if (msg['direction'] == 3) {
		//用户在从右向左滑动，切换到下一屏，将该屏幕的播放时间，设置为5分钟（也就是如果5分钟没有操作.则继续轮播）
		logDebug("当前播放的索引=" + cScreenObj.index)
		if (_queueRolling.length == 1) {
			return;
		}
		if (cScreenObj.index < (_queueRolling.length - 1)) {
			var nextIndex = cScreenObj.index + 1;
			logDebug("播放下一个=" + nextIndex)
			startPlay(nextIndex);
		} else {
			logDebug("从头开始播放")
			startPlay(0);
		}
		cScreenObj.duration = delayed;
	} else if (msg['direction'] == 4) {
		//用户在从左向右滑动，切换到下一屏，将该屏幕的播放时间，设置为5分钟（也就是如果5分钟没有操作.则继续轮播）
		logDebug("当前播放的索引=" + cScreenObj.index)
		if (_queueRolling.length == 1) {
			return;
		}
		if (cScreenObj.index >0) {
			var nextIndex = cScreenObj.index - 1;
			logDebug("播放下一个=" + nextIndex)
			startPlay(nextIndex);
		} else {
			logDebug("从头开始播放")
			startPlay((_queueRolling.length - 1));
		}
		cScreenObj.duration = delayed;
	} else if (msg['direction'] == 0) {
		//用户没有滑动，但是有点击屏幕，将当前播放的屏幕播放时间延长到5分钟，此时间，可以配置
		cScreenObj.duration = delayed;
	}
}
function playContentList() {
	//获取当前播放的对象，索引、播放时长，定时切换到下一个，或者启动指定时间需要启动的内容。
	var now = new Date().getTime(); //毫秒
	var t = now / 1000 - cScreenObj.starttime / 1000;

	//检查有无到时间需要播放的内容
	var topwebview = plus.webview.getTopWebview();
	if (_queueFixedtime[new Date().format('hh:mm')]) {
		startPlayFixedtime(_queueFixedtime[new Date().format('hh:mm')])
	} else if (_queueFixedtime[new Date().format('yyyy-MM-dd hh:mm')]) {
		startPlayFixedtime(_queueFixedtime[new Date().format('yyyy-MM-dd hh:mm')])
	} else {
		if (cScreenObjFixedtime.winid) {
			//说明有定时任务正在播放，检查是否已满足设定的播放时间
			var t1 = now / 1000 - cScreenObjFixedtime.starttime / 1000;
			if (t < cScreenObjFixedtime.duration) {
				//继续播放定时任务
				return;
			} else {
				cScreenObjFixedtime.winid = null;
				cScreenObj.duration = 0; //设置播放时间为0，方便后面快速切换下一内容
			}
		}
		if (t >= cScreenObj.duration) {
			if (_queueRolling.length == 1) {
				return;
			}
			if (cScreenObj.index < (_queueRolling.length - 1)) {
				var nextIndex = cScreenObj.index + 1;
				logDebug("播放下一个=" + nextIndex)
				startPlay(nextIndex);
			} else {
				logDebug("从头开始播放")
				startPlay(0);
			}
		}
	}
}

function pushLoadContentPage(data) {
	logDebug("pushLoadContentPage:" + JSON.stringify(data));
	
	if(data["contentlist"]){
		for (var i=0;i< data["contentlist"].length;i++) {
			data["contentlist"][i]["url"] = VisualConst.appendDeviceParam(data["contentlist"][i]["url"]);
		}
		//关闭当前正在播放的内容
		
	}
	logDebug("替换设备位置参数:" + JSON.stringify(data));
	if (data && data['pushtype'] == 'screens') {
		
		createScreens(data);
	}
}
//收到服务端推送的消息时
function clientIndexHandleMessage(data) {
	
	switch (data.pushtype) {
		case 'screens':
			//展示内容
			VisualConst.setLastContent(data);
			pushLoadContentPage(data);
			break;
		case 'event':
			//用来扩展 比如 要求客户端截图 ，获取客户端内存信息,主动触发更新 等场景
			logDebug(data);
			clientIndexEvent(data);
			break;
	}
}

function connectWsServer() {
	var serverInfo = VisualConst.getServerInfo();
	var wsParams = _cfg.getRCfg();
	//logDebug(JSON.stringify(____clientStaticData));
	wsParams["ws_ip"] = serverInfo["ip"] || wsParams["ws_ip"];
	wsParams["ws_port"] = serverInfo["port"] || wsParams["ws_port"];
	wsParams["token"] = serverInfo["token"] || "";
	wsParams['deviceid'] = ____clientStaticData["_customDevice"]["deviceid"];
	wsParams['deviceip'] = ____clientStaticData["networkinfo"]["address"]["deviceip"];
	wsParams['reconnInterval'] = 2000;
	wsParams["appid"] = VisualConst.getAppCfg()['comm']['appid'];
	initScreenWs(wsParams); //链接服务
}

function setStatusText(status) {
	document.getElementById("sys_status").innerHTML = status;
}

function clientIndexHandleWsConn(event, e, ws) {
	//"onclose" onopen
	if (event == "onclose") {
		//1，关闭展示内容
		//2，设置状态显示
		//console.log("onclose 已断开连接");
		setStatusText("已断开连接");
	} else if (event == "onopen") {
		var msg = {
			errcode: '100000',
			errmsg: 'open websocket'
		};
		var status = "已连接";
		status +="<br>设备ID: " + ____clientDeviceInfo["id"];
		status +="<br>设备IP: " + ____clientDeviceInfo["ip"];
		setStatusText(status);//显示已连接的服务器IP，当前本机的IP、ID
		//重新加载客户端信息
		reConnectOpen();
	} else if (event == "onerror") {
		var msg = {
			errcode: '100500',
			errmsg: 'close websocket'
		};
		//console.log("onerror暂时无法连接服务" + JSON.stringify(e));
		setStatusText("暂时无法连接服务");
		closeStartPage();
	}
};
